/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import grails.util.Environment

import org.ibiblio.terasaur.bt.Torrent
import org.ibiblio.terasaur.item.Item
import org.ibiblio.terasaur.user.Role
import org.ibiblio.terasaur.lookups.LookupValueImporter
import org.ibiblio.terasaur.item.Collection
import org.codehaus.groovy.grails.plugins.springsecurity.acl.AclClass
import org.codehaus.groovy.grails.commons.ConfigurationHolder

class BootStrap {
    def init = { servletContext ->
        _addRoles()
        _addAclClasses()
        LookupValueImporter.importAll()
        _checkTorrentsRoot()
    }

    private void _addRoles() {
        // Roles for spring security
        def userRole = Role.findByAuthority('ROLE_USER') ?: new Role(authority: 'ROLE_USER').save(insert:true, flush:true, failOnError: true)
        def adminRole = Role.findByAuthority('ROLE_ADMIN') ?: new Role(authority: 'ROLE_ADMIN').save(insert:true, flush:true, failOnError: true)
        def createItemRole = Role.findByAuthority('ROLE_CAN_CREATE_ITEM') ?: new Role(authority: 'ROLE_CAN_CREATE_ITEM').save(insert:true, flush:true, failOnError: true)
    }

    private void _addAclClasses() {
        _ensureAclClassCreated('org.ibiblio.terasaur.item.Item')
        _ensureAclClassCreated('org.ibiblio.terasaur.item.Collection')
        _ensureAclClassCreated('org.ibiblio.terasaur.bt.Seedbank')
        _ensureAclClassCreated('org.ibiblio.terasaur.bt.SeedbankTorrent')
    }

    private void _ensureAclClassCreated(className) {
        def aclClass = AclClass.findByClassName(className) ?: new AclClass(className:className).save(insert:true, flush:true, failOnError: true)
    }

    private void _checkTorrentsRoot() {
        def config = ConfigurationHolder.config
        def torrentsRoot = config.terasaur.torrent.root
        // TODO: how to make logging work here?
        //log.debug("Using torrent file root directory: " + torrentRoot)
        def torrentsRootFile = new File(torrentsRoot)
        if (!torrentsRootFile.exists()) {
            //log.debug("Creating torrent file root directory")
            if (!torrentsRootFile.mkdirs()) {
                throw new IOException("Unable to create torrent file root directory (" + torrentsRoot + ")")
            }
        }
        def test = torrentsRoot + File.separator + "write_test"
        def testFile = new File(test)
        if (!testFile.createNewFile()) {
            throw new IOException("Unable to write test file (" + test + ")")
        }
        testFile.delete()
    }

    def destroy = {
    }
}
